package com.asyf.demo.service.impl;

import cn.hutool.core.io.resource.ClassPathResource;
import com.asyf.demo.service.DownloadService;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @Author yjz
 * @Date 2022/9/20 9:42
 */
@Service
public class DownloadServiceImpl implements DownloadService {


    //下载excel模板
    @Override
    public void downloadExcel(HttpServletResponse response, String path, String fileName) throws Exception {
        // 将文件名称进行编码
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("content-type:octet-stream");
        OutputStream outputStream = response.getOutputStream();
        ClassPathResource resource = new ClassPathResource(path);
        //方式二
        FileCopyUtils.copy(resource.getStream(), outputStream);

        //方式一
        InputStream inputStream = null;
        try {
            //读取服务器端模板文件
//            inputStream = resource.getStream();
//            //将流中内容写出去
//            outputStream = response.getOutputStream();
//            byte[] buffer = new byte[1024];
//            int len;
//            while ((len = inputStream.read(buffer)) != -1) {
//                outputStream.write(buffer, 0, len);
//            }
//            outputStream.flush();
        } finally {
//            if (inputStream != null) {
//                inputStream.close();
//            }
//            if (outputStream != null) {
//                outputStream.close();
//            }
        }
    }

    @Override
    public void downloadAndEdit(HttpServletResponse response, String path, String fileName) throws Exception {
        // 将文件名称进行编码
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("content-type:octet-stream");
        try (OutputStream outputStream = response.getOutputStream();) {
            ClassPathResource resource = new ClassPathResource(path);

            XSSFWorkbook workbook = new XSSFWorkbook(resource.getFile());
            XSSFSheet sheet = workbook.getSheetAt(0);

            //新增单元格数据
            XSSFRow row = sheet.getRow(0);
            XSSFCell cell = row.createCell(5);
            cell.setCellValue("下拉选项");

            //添加校验
            String[] options = new String[]{"选项一", "选项二", "选项三",};
            addValidation(sheet, 1, 100, 5, 5, options);

            workbook.write(outputStream);
        }
    }

    /**
     * 添加下拉选择
     *
     * @param sheet
     * @param firstRow
     * @param lastRow
     * @param firstCol
     * @param lastCol
     * @param options
     */
    private void addValidation(XSSFSheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, String[] options) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        //设置下拉框数据
        DataValidationConstraint constraint = helper.createExplicitListConstraint(options);
        //设置生效的起始行、终止行、起始列、终止列
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        DataValidation validation = helper.createValidation(constraint, addressList);
        //适配xls和xlsx
        if (validation instanceof HSSFDataValidation) {
            validation.setSuppressDropDownArrow(false);
        } else {
            validation.setSuppressDropDownArrow(true);
            validation.setShowErrorBox(true);
        }
        sheet.addValidationData(validation);
    }

}
